package com.thinkgem.jeesite.modules.sys.web;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.entity.Student;
import com.thinkgem.jeesite.modules.sys.service.StudentService;
import com.thinkgem.jeesite.modules.sys.utils.ResponseEnum;
import com.thinkgem.jeesite.modules.sys.utils.ResponseObject;
@Controller
@RequestMapping(value = "${adminPath}/sys/student")
public class StudentController extends BaseController {
	
	@Autowired
	private StudentService studentService;
	
	@ModelAttribute
	public Student get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return studentService.get(id);
		}else{
			return new Student();
		}
	}
	/*
	@RequiresPermissions("sys:student:view")
	@RequestMapping(value = {"list", ""})
	@ResponseBody
	public  ResponseObject<?> list(Student student, HttpServletRequest request, HttpServletResponse response){
		try {
			@SuppressWarnings("unused")
			ResponseObject<Page<Student>> responseObject = new ResponseObject<Page<Student>>();
			Page<Student> page = studentService.findPage(new Page<Student>(request, response), student);
			return ResponseObject.successResponse(page);
		} catch (Exception e) {
			logger.debug("查询失败"+e.getMessage());
			return ResponseObject.failResponse();
		}
	}*/
	@RequiresPermissions("sys:student:view")
	@RequestMapping(value = {"list", ""})
	public  String list(Student student, HttpServletRequest request, HttpServletResponse response,Model model){
		
			List<Student> studentList = studentService.findList(student);
			model.addAttribute(studentList);
			Page<Student> page = studentService.findPage(new Page<Student>(request, response), student);
			model.addAttribute(page);
			return "modules/school/studentList";
		 
	}
	
	
	
	@RequiresPermissions("sys:student:view")
	@RequestMapping(value = "form")
	public  String form(Student student , Model model){
		model.addAttribute("student",student);
		return "modules/school/studentForm";
	}
	
	@RequiresPermissions("sys:student:save")
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(Student student, Model model, RedirectAttributes redirectAttributes){
			
			if (Global.isDemoMode()) {
				addMessage(redirectAttributes, "演示模式，不允许操作！");
				return "redirect:" + adminPath + "/sys/student/?repage";
			}
			if (!beanValidator(model, student)){
				return form(student, model);
			}
			studentService.save(student);
			addMessage(redirectAttributes, "保存学生'" + student.getId() + "'成功");
			return "redirect:" + adminPath + "/sys/student/?repage&type";
	}
	
	/*@RequiresPermissions("sys:student:save")
	@RequestMapping(value = "save")
	@ResponseBody
	public ResponseObject<?> save(Student student){
			
			if (Global.isDemoMode()) {
				return ResponseObject.failResponse(ResponseEnum.sys_is_demo_mode);
			}
			beanValidator(student);
			student.setIsNewRecord(true);
			studentService.idValidator(student.getId());
			studentService.sNoValidator(student.getsNo());
			studentService.save(student);
			return ResponseObject.successResponse();
	}
	*/
	@RequiresPermissions("sys:student:save")
	@RequestMapping(value = "getId")
	@ResponseBody
	public ResponseObject<?> getId(){
		try {
			if (Global.isDemoMode()) {
				return ResponseObject.failResponse(ResponseEnum.sys_is_demo_mode);
			}
			String id = studentService.getId();
			return ResponseObject.successResponse(id);
		} catch (Exception e) {
			 logger.debug("生成主键"+e.getMessage());
			 return ResponseObject.failResponse();
		}
	}
	
	@RequiresPermissions("sys:student:save")
	@RequestMapping(value = "getSno")
	@ResponseBody
	public ResponseObject<?> getSno(){
		try {
			if (Global.isDemoMode()) {
				return ResponseObject.failResponse(ResponseEnum.sys_is_demo_mode);
			}
			String sNo = studentService.getSno();
			return ResponseObject.successResponse(sNo);
		} catch (Exception e) {
			 logger.debug("生成学号失败"+e.getMessage());
			 return ResponseObject.failResponse();
		}
	}
	/**
	 * 
	 * @Title: exportFile   
	 * @Description: 批量导出 
	 * @param: @param student
	 * @param: @param request
	 * @param: @param response
	 * @param: @return      
	 * @return: ResponseObject<?>      
	 * @throws
	 */
	//@RequiresPermissions("sys:student:view")
	@RequestMapping(value = "export",method = RequestMethod.GET)
	@ResponseBody
	public ResponseObject<?> exportFile(HttpServletRequest request, HttpServletResponse response){
		try {
			if (Global.isDemoMode()) {
				return ResponseObject.failResponse(ResponseEnum.sys_is_demo_mode);
			}
			Student student = new Student();
			String fileName = "学生数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			Page<Student> page = studentService.findPage(new Page<Student>(request, response,-1), student);
			new ExportExcel("学生数据", Student.class).setDataList(page.getList()).write(response,fileName).dispose();
			return ResponseObject.successResponse();
		} catch (Exception e) {
			 logger.debug("批量导出学生数据失败："+e.getMessage());
			 return ResponseObject.failResponse();
		}
	}
	
	@RequiresPermissions("sys:student:save")
	@RequestMapping(value = "import",method = RequestMethod.POST)
	@ResponseBody
	public ResponseObject<?> importFile(MultipartFile file){
		try {
			if (Global.isDemoMode()) {
				return ResponseObject.failResponse(ResponseEnum.sys_is_demo_mode);
			}
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel importExcel =new ImportExcel(file, 1 ,0);
			List<Student> list = importExcel.getDataList(Student.class);
			for (@SuppressWarnings("unused") Student student : list) {
			//ch
			}
			if (failureNum>0) {
				failureMsg.insert(0, "导入失败:"+failureNum+"条,导入信息如下：");
			}
			logger.info("已经成功导入："+successNum+"条记录"+failureMsg);;
			return ResponseObject.successResponse(ResponseEnum.sucess.getCode(),failureMsg.toString());
		} catch (Exception e) {
			 logger.debug("导入学生失败："+e.getMessage());
			 return ResponseObject.failResponse();
		}
	}
	
	/**
	 * 
	 * @Title: importFileTemplate   
	 * @Description:  
	 * @param: @param student
	 * @param: @param request
	 * @param: @param response
	 * @param: @return      
	 * @return: ResponseObject<?>      
	 * @throws
	 */
	@RequiresPermissions("sys:student:view")
	@RequestMapping(value = "import/template")
	@ResponseBody
	public ResponseObject<?> importFileTemplate(Student student,HttpServletRequest request, HttpServletResponse response){
		try {
			if (Global.isDemoMode()) {
				return ResponseObject.failResponse(ResponseEnum.sys_is_demo_mode);
			}
			String fileName = "学生数据导入模板"+".xlsx";
			List<Student> list = Lists.newArrayList();
			list.add(null);
			new ExportExcel("学生数据", Student.class,2).setDataList(list).write(response,fileName).dispose();
			return ResponseObject.successResponse();
		} catch (Exception e) {
			 logger.debug("生成学号失败"+e.getMessage());
			 return ResponseObject.failResponse();
		}
	}
	
	public ResponseObject<?> uploadFile(@RequestParam(value="file",required = false) MultipartFile file,HttpServletRequest request,HttpServletResponse response){
		try {
			logger.info("上传文件 start=============");
			studentService.uploadFile(file,request,response);
		} catch (IllegalStateException | IOException e) {
			logger.info("上传文件失败"+e.getMessage());
			return ResponseObject.failResponse(ResponseEnum.file_upload_fail);
		}
		try {
			logger.info("导入数据 start=======================");
			Map<String, Object> mapList = studentService.importFile(file);
			logger.info("导入数据 end =================");
			return ResponseObject.successResponse(mapList);
			
		} catch (Exception e) {
			logger.info("student表数据插入失败"+e.getMessage());
			return ResponseObject.failResponse(ResponseEnum.student_export_fail);
		}
		
	}
	
	
	
}
